package user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import core.constants.Constant;
import core.domain.ListDataInfo;
import core.domain.PageQuery;
import core.threadLocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import user.domain.message.vo.MessageTextVO;
import user.manager.MessageCacheManage;
import user.mapper.MessageTextMapper;
import user.service.IUserMessageService;

import java.util.List;

@Service
public class UserMessageServiceImpl implements IUserMessageService {

    @Autowired
    private MessageCacheManage messageCacheManage;

    @Autowired
    private MessageTextMapper messageTextMapper;
    @Override
    public ListDataInfo list(PageQuery dto) {
        Long userId = ThreadLocalUtils.get(Constant.USER_ID, Long.class);
        Long total = messageCacheManage.getListSize(userId);
        List<MessageTextVO> messageTextVOList;
        if(total == null || total <= 0){
            PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
            messageTextVOList = messageTextMapper.selectUserMessageList(userId);
            messageCacheManage.refreshCache(userId, messageTextVOList);
            total = new PageInfo<>(messageTextVOList).getTotal();
        } else {
            messageTextVOList = messageCacheManage.getMessageTextVOList(dto, userId);
        }
        if(CollectionUtil.isEmpty(messageTextVOList)){
            return ListDataInfo.empty();
        }
        return ListDataInfo.success(messageTextVOList, total.intValue());
    }
}
